﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Dynamic;
using FluorineFx.Json;

namespace lxwmvc
{
    /// <summary>
    /// 还款
    /// </summary>
    public static partial class huifucontroller
    {

        /// <summary>

        /// </summary>
        /// <param name="pb"></param>
        //public static void huifu_chongzhi(pagebase pb)
        //{
            
        //}
        #region 放款成功后，根据投标需求，给借款人生成还款计划，就是每期应该还款多少.start  同步方法
        /// <summary>
        /// 异步通知，是否成功。
        /// </summary>
        public static void huifu_huankuan_returnbg(pagebase pb)
        {
            RetRepayment objrev = new RetRepayment();
            //后台调用，最终要打印出来参数
            core_huifu.ReturnUrl(HttpContext.Current, "OrdId", objrev, true);
            core_huifu.saveHuiFuLiuShui(objrev);

            if (objrev.RespCode == core_huifu.HUIFU_SUCCESS)
            {
                supermodel Mautopayback = supermodel.create("Mautopayback");
                //返回原来投标记录的主键
                Mautopayback["Mautopaybackid"] = objrev.MerPriv + "";
                //Mautoappropriation["FreezeTrxId"] = objrev.FreezeTrxId;
                //Mautoappropriation["TrxId"] = objrev.TrxId;
                //续费收取对象标志 I/O
                Mautopayback["FeeObjFlag"] = objrev.FeeObjFlag;
                Mautopayback["MerCustId"] = objrev.MerCustId;//客户号
                //代表放款成功
                Mautopayback["logtype"] = "1";
                //更新信息
                Mautopayback.saveorupdate();
            }
        }

        ///// <summary>
        ///// 还款发送验证码
        ///// </summary>
        //[SkipFilter()]
        //public void sendcode(string phone, string biaoti, decimal tzjine)
        //{
        //    List<ErrorMessage> oplist = new List<ErrorMessage>();
        //    try
        //    {
        //        //如果已经发送 就验证发送了多长时间
        //        if (Session["phonecode"] != null)
        //        {
        //            string sql = " select CodeTime from SysUser_kuozhan where user_id='" + HttpContext.Current.Session["g_user_id"].ToString() + "'";
        //            string time = jiandansql.getstring(sql);
        //            if (time != "")
        //            {
        //                TimeSpan CodeTime = time.todatetime() - DateTime.Now;
        //                if (time.todatetime() > DateTime.Now)
        //                {
        //                    oplist[0] = (new ErrorMessage() { error = 0, msg = "您已获取验证码!请" + CodeTime.Minutes + "分钟后重试!" });
        //                    string json = JsonHelper.JsonSerializer(oplist);
        //                    RenderText(json);
        //                    return;
        //                }
        //            }
        //            Session.Remove("phonecode");
        //        }

        //        string code = codehelper.GetRandomString(4);
        //        Session["code"] = code;
        //        Session["CodeTime"] = DateTime.Now.AddMinutes(5);//5分钟
        //        Session["phonecode"] = phone + "_" + code;
        //        Session["codesum"] = "5";//验证5次

        //        //发送短信验证码
        //        string senSMS = "您正在对【" + biaoti + "】进行还款，本次还款金额" + tzjine + "元，验证码： " + code + " 。如非本人操作，请忽略！";
        //        //Response.Write(senSMS);
        //        if (!SMSApp.SendMsg(phone, senSMS))
        //        {
        //            oplist.Clear();
        //            oplist.Add(new ErrorMessage() { error = 0, msg = "发送短信验证码失败" });
        //            RenderText(JsonHelper.JsonSerializer(oplist));
        //            return;
        //        }

        //        oplist.Clear();
        //        oplist.Add(new ErrorMessage() { error = 1, msg = "发送成功!" });
        //        RenderText(JsonHelper.JsonSerializer(oplist));
        //        return;
        //    }
        //    catch (Exception ex)
        //    {
        //        dataloger.writelog(ex);
        //        oplist.Clear();
        //        oplist.Add(new ErrorMessage() { error = 0, msg = "获取验证码失败!" });
        //        RenderText(JsonHelper.JsonSerializer(oplist));
        //        return;
        //    }
        //}

        /// <summary>
        /// 还款操作
        /// </summary>
        /// <param name="pb"></param>
        public static void huifu_huankuan_yonghu(pagebase pb)
        {
            //按照计划，每次还款金额加上利息，还给投资人。

            //这里需要得到一些信息
            //首先需要得到标的相关信息
            //其次要得到投资人列表
            //然后是还款金额（分期本金+利息）
            int proid = pb.v_i("proid");
            //todo 获取到所有投资该产品的投标记录，这些记录已经成功。
            
            var list = supermodel.create("Mmanualbid").where("LogType='1' and proid=" + proid).list();

            //循环进行放款
            foreach (supermodel model in list)
            {
                huifu_huankuan_model(model);
            }
        }

        private static void huifu_huankuan_model(supermodel model)
        {
            Repayment objsend = new Repayment();


            //objsend.OrdId = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            //objsend.OrdDate = DateTime.Now.ToString("yyyyMMdd");
            objsend.OutCustId = model["BorrowerCustId"] + "";

            //也是跟投标的时候 订单号和日期一致。
            objsend.SubOrdId = model["OrdId"] + "";
            objsend.SubOrdDate = model["OrdDate"] + "";

            objsend.OutAcctId = "";

            //返款金额，这里需要计算，到底给该用户返款多少，需要计算出来这次返款+利息
            objsend.TransAmt = model["TransAmt"] + "";

            objsend.Fee = ConfigurationManager.AppSettings["RepaymentFee"];//费率为0
            objsend.InCustId = model["UsrCustId"] + "";
            objsend.InAcctId = "";
            objsend.DivDetails = "";
            objsend.DivCustId = "";
            objsend.DivAcctId = "";
            objsend.DivAmt = "";
            objsend.FeeObjFlag = "";
            objsend.BgRetUrl = ConfigurationManager.AppSettings["LocalUrl"] + "ploan/zidonghuankuanreturnbg.html";
            objsend.ReqExt = "";
            objsend.ProId = "";

            //进行调用之前，先产生流水  操作这个表dbo.Mautopayback 把里面的信息补充完整
            supermodel data = supermodel.create("Mautopayback");
            //data["xxxx"] = "xxxx";
            //LogType 0 代表未处理，1代表已经处理
            data["LogType"] = "0";
            data["User_Id"] = HttpContext.Current.Session["g_user_id"].ToString(); ;//用户ID
            data["OrdId"] = model["OrdId"] + "";//订单号    
            data["SubOrdDate"] = objsend.SubOrdDate + "";//设置日期
            data["OrdDate"] = objsend.OrdDate + "";//订单日期
            data["OutCustId"] = model["BorrowerCustId"] + ""; //出账客户号
            data["TransAmt"] = model["TransAmt"] + "";//交易金额
            data["SubOrdId"] = model["OrdId"] + "";//订单号
            data["InCustId"] = model["UsrCustId"] + "";//入账客户号
            data["ProId"] = model["proid"].tostr();//入账客户号
            var ret = data.saveorupdate();

            //把主键设置上
            objsend.MerPriv = ret.identity + "";


            var r = core_huifu.Send<RetRepayment>(objsend);
            if (r.RespCode == core_huifu.HUIFU_SUCCESS)
            {
                supermodel Mautopayback = supermodel.create("Mautopayback");
                //返回原来投标记录的主键
                Mautopayback["Mautopaybackid"] = r.MerPriv + "";
                //Mautoappropriation["FreezeTrxId"] = objrev.FreezeTrxId;
                //Mautoappropriation["TrxId"] = objrev.TrxId;
                Mautopayback["FeeObjFlag"] = r.FeeObjFlag;//续费收取对象标志 I/O
                Mautopayback["MerCustId"] = r.MerCustId;//客户号
                //代表放款成功
                Mautopayback["logtype"] = "1";
                //更新信息
                data.saveorupdate();

            }
        }

        /// <summary>
        /// 手动还款，前台用户直接点击
        /// </summary>
        /// <param name="pb"></param>
        public static void huifu_huankuan_shoudonghuankuan(pagebase pb)
        {
            int error = 0;
            //按照计划，每次还款金额加上利息，还给投资人。
            //这里需要得到一些信息
            //首先需要得到标的相关信息
            //其次要得到投资人列表
            //然后是还款金额（分期本金+利息）
            var phkid = pb.v_i("phkid");

            //通过还款表，计算出来这期还款信息
            _phk drhk = queryhelper.get<_phk>("select pjkjbxxid,qishu,huankuanrenid,jiekuanbiaoti,(huankuanbenjin+lixi) as benxi  from phk where phkid=" + phkid);
            
            //该标的基本信息
            _pjkjbxx drpjkjbxx = queryhelper.get<_pjkjbxx>(" select nianlilv,qixian,huankuanfangshi  from pjkjbxx where pjkjbxxid=" + drhk["pjkjbxxid"].tostr());


            //计算这期的全部本息
            Decimal benxi = queryhelper.get("select SUM(Principal+Interest) from Project_TouZiJiLu where PlanStatus=0 AND  phkid=" + phkid).todecimal(0);

            //收益状态   【0/待收益】【2/已收益】【3/债券转让】
            //查找所有未收益且有效（）的收益计划
            ////计算未转让债权的,正常投资的信息
            var sqlList = "SELECT * FROM Project_TouZiJiLu WHERE PlanStatus=0 AND phkid=" + phkid;

            //todo 获取到投资该产品的投标记录，这些记录已经成功。shifouzhuanrang标识是否为转让债权
            //var sql = "select *,(select jiekuanjine from pjkjbxx where pjkjbxx.pjkjbxxid=Mmanualbid.ProId) as jiekuanjine,(select top 1 ProId from zhaiquanzhuanrang inner join  Mzhaiquanliushui on zhaiquanzhuanrang.pjkjbxxid=Mzhaiquanliushui.ProId where oldpjkjbxxid=" + drhk["pjkjbxxid"].tostr() + " and LogType=1) as shifouzhuanrang from Mmanualbid where LogType='1' and proid=" + drhk["pjkjbxxid"].tostr();
            var list = queryhelper.query<supermodel>(sqlList);


            var table = queryhelper.query<supermodel>("select youxiaojine from Project_TouZiJiLu where PlanStatus=0 and youxiaojine>0 AND  phkid=" + phkid);

            double zlx = 0; //总利息
            
            //体验金这部分，如果下次用，就直接出现问题了。
            //计算体验金的利息,这部分是虚拟资金，主要用于计算体验金
            DataTable dtlx = new DataTable();
            if (table.Count() > 0)
            {
                if (drpjkjbxx["huankuanfangshi"].toint16(0) == 488 || drpjkjbxx["huankuanfangshi"].toint16(0) == 481)
                {
                    dtlx = core_p2p.JiSuanShouYiByDay(table.ElementAt(0)["youxiaojine"].todouble(0), drpjkjbxx["nianlilv"].todouble(0), drpjkjbxx["qixian"].toint16(0), DateTime.Now, drpjkjbxx["huankuanfangshi"].toint16(0), out zlx);
                }
                else
                {
                    dtlx = core_p2p.Tools(table.ElementAt(0)["youxiaojine"].todouble(0), drpjkjbxx["nianlilv"].todouble(0), DateTime.Now, DateTime.Now.AddMonths(drpjkjbxx["qixian"].toint16(0)).AddDays(-1), drpjkjbxx["huankuanfangshi"].toint16(0), out zlx);
                }

                if (dtlx.Rows[0]["lixi"].tostr() != "")
                {
                    benxi = benxi - (decimal.Parse(dtlx.Rows[0]["lixi"].tostr()) * table.Count());
                }
            }

            //验证当前余额是否大于还款金额
            try
            {
                string zongjine = "";
                string dongjieyue = "";
                if (Decimal.Parse(huifu_chaxun_yue(core_user.userID, out zongjine, out dongjieyue, false)) < benxi)
                {
                    //jshelper.alert("您的账户余额不足！");
                    return;
                }
            }
            catch
            {
                //jshelper.alert("您的账户余额不足！");
                return;
            }

            #region 债权还款


            //查找所有未收益且有效（）的收益计划，这里是查找债权的信息
            //债权的试图
            var sqlZhaiQuanList = "SELECT * FROM Project_ZhaiQuanJiLu WHERE PlanStatus=0 AND phkid=" + phkid;

            //todo 获取到投资该产品的投标记录，这些记录已经成功。shifouzhuanrang标识是否为转让债权
            //var sql = "select *,(select jiekuanjine from pjkjbxx where pjkjbxx.pjkjbxxid=Mmanualbid.ProId) as jiekuanjine,(select top 1 ProId from zhaiquanzhuanrang inner join  Mzhaiquanliushui on zhaiquanzhuanrang.pjkjbxxid=Mzhaiquanliushui.ProId where oldpjkjbxxid=" + drhk["pjkjbxxid"].tostr() + " and LogType=1) as shifouzhuanrang from Mmanualbid where LogType='1' and proid=" + drhk["pjkjbxxid"].tostr();
            var zhaiquanlist = queryhelper.query<supermodel>(sqlZhaiQuanList);

            foreach (IDictionary<string,object> dr in zhaiquanlist)
            {
                Repayment objsend = new Repayment();

                //objsend.OrdId = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                //objsend.OrdDate = DateTime.Now.ToString("yyyyMMdd");
                objsend.OutCustId = dr["BorrowerCustId"] + "";

                //也是跟投标的时候 订单号和日期一致。
                objsend.SubOrdId = dr["OrdId"] + "";
                objsend.SubOrdDate = dr["OrdDate"] + "";
                objsend.OutAcctId = "";

                //返款金额，这里需要计算，到底给该用户返款多少，需要计算出来这次返款+利息
                Decimal PrincipalInterest = decimal.Parse(dr["Principal"].ToString()) + decimal.Parse(dr["Interest"].ToString());
                Decimal amt = PrincipalInterest;

                //判断是否使用优惠金,则减去优惠金的利息
                if (decimal.Parse(dr["youxiaojine"].ToString()) > 0)
                {

                    //用户还的利息=总利息-体验金利息
                    amt = amt - decimal.Parse(dtlx.Rows[0]["lixi"].tostr());

                    //商户给投资人的优惠金的利息
                    //shanghutuihuan(dr["toubiaorenid"].ToString(), decimal.Parse(dtlx.Rows[0]["lixi"].tostr()));
                }

                objsend.TransAmt = amt.ToString("#0.00") + "";

                objsend.Fee = HuiFuArg.RepaymentFee;//费率为0
                objsend.InCustId = dr["BuyCustId"] + "";
                objsend.InAcctId = "";
                objsend.DivDetails = "";
                objsend.DivCustId = "";
                objsend.DivAcctId = "";
                objsend.DivAmt = "";
                objsend.FeeObjFlag = "";
                objsend.BgRetUrl = HuiFuArg.LocalUrl + "huifu/huifu_huankuan_shoudonghuankuan_returnbg.html";
                objsend.ReqExt = "";
                objsend.ProId = "";

                //进行调用之前，先产生流水  操作这个表dbo.Mautopayback 把里面的信息补充完整
                supermodel data = supermodel.create("Mautopayback");
                //data["xxxx"] = "xxxx";
                //LogType 0 代表未处理，1代表已经处理
                data["LogType"] = "0";
                data["User_Id"] = HttpContext.Current.Session["g_user_id"].ToString(); ;//用户ID
                data["OrdId"] = dr["OrdId"] + "";//订单号    
                data["SubOrdDate"] = objsend.SubOrdDate + "";//设置日期
                data["OrdDate"] = objsend.OrdDate + "";//订单日期
                data["OutCustId"] = dr["BorrowerCustId"] + ""; //出账客户号
                data["TransAmt"] = amt.ToString("#0.00") + ""; //交易金额
                data["SubOrdId"] = dr["OrdId"] + "";//订单号
                data["InCustId"] = dr["BuyCustId"] + "";//入账客户号
                //data["ProId"] = proid.tostr();//入账客户号
                var ret = data.saveorupdate();


                //把主键设置上
                objsend.MerPriv = ret.identity + "";


                var r = core_huifu.Send<RetRepayment>(objsend);
                if (r.RespCode == core_huifu.HUIFU_SUCCESS)
                {
                    supermodel Mautopayback = supermodel.create("Mautopayback");
                    //返回原来投标记录的主键
                    Mautopayback["Mautopaybackid"] = r.MerPriv + "";
                    //Mautoappropriation["FreezeTrxId"] = objrev.FreezeTrxId;
                    //Mautoappropriation["TrxId"] = objrev.TrxId;
                    Mautopayback["FeeObjFlag"] = r.FeeObjFlag;//续费收取对象标志 I/O
                    Mautopayback["MerCustId"] = r.MerCustId;//客户号
                    //代表放款成功
                    Mautopayback["logtype"] = "1";
                    //更新信息
                    Mautopayback.saveorupdate();
                    //更新还款计划表状态

                    //生成还款计划明细记录
                    supermodel datahkmingxi = supermodel.create("phkmingxi");
                    datahkmingxi["pjkjbxxid"] = drhk["pjkjbxxid"].tostr();
                    datahkmingxi["jiekuanbiaoti"] = drhk["jiekuanbiaoti"].tostr();
                    datahkmingxi["qishu"] = drhk["qishu"] + "";
                    datahkmingxi["phkid"] = phkid;
                    datahkmingxi["user_id"] = core_user.getUserIdByUsrCustId(dr["BuyCustId"]+"");
                    datahkmingxi["huankuanjine"] = amt.ToString("#0.00") + "";
                    datahkmingxi["zhuangtai"] = "已还款";
                    datahkmingxi["huankuanrenid"] = HttpContext.Current.Session["g_user_id"].ToString() + "";
                    datahkmingxi["huankuanleixing"] = "手动还款";
                    datahkmingxi.saveorupdate();

                    //这句话是不是写的让人？？？？？
                    //int result = jiandansql.execute(" UPDATE  Project_ZhaiQuanJiLu SET [PlanStatus]=2 WHERE [PlanStatus]=0 AND phkid=" + phkid + " AND  [OrdId]='" + dr["OrdId"].tostr() + "' AND [OrdDate]='" + dr["OrdDate"].tostr() + "'");

                    //发送短信
                    //string MOBIL_NO = jiandansql.getstring("select MOBIL_NO from SysUser where user_id='" + dr["toubiaorenid"].ToString() + "'");
                    //SMSApp.SendMsg(MOBIL_NO, "亲爱的嘉金投资用户,您好！感谢您使用互联网理财投资平台嘉金网。您投资的理财产品您于" + DateTime.Now.ToString("F") + "成功开户。若非本人操作，请您联系致电客服。400-100-0616");
                    ////发送站内信
                    //P2PHelper.sendMessage(dr["toubiaorenid"].ToString(), "亲爱的嘉金投资用户,您于" + DateTime.Now.ToString("F") + "成功开户。若非本人操作，请您联系致电客服。400-100-0616");
                }
                else { error++; }

            }

            #endregion

            //循环进行放款
            foreach (IDictionary<string,object> dr in list)
            {
                Repayment objsend = new Repayment();

                objsend.OrdId = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                objsend.OrdDate = DateTime.Now.ToString("yyyyMMdd");
                objsend.OutCustId = dr["BorrowerCustId"] + "";

                //也是跟投标的时候 订单号和日期一致。
                objsend.SubOrdId = dr["OrdId"] + "";
                objsend.SubOrdDate = dr["OrdDate"] + "";
                objsend.OutAcctId = "";

                //返款金额，这里需要计算，到底给该用户返款多少，需要计算出来这次返款+利息
                Decimal PrincipalInterest = decimal.Parse(dr["Principal"].ToString()) + decimal.Parse(dr["Interest"].ToString());
                Decimal amt = PrincipalInterest;

                //判断是否使用优惠金,则减去优惠金的利息
                if (decimal.Parse(dr["youxiaojine"].ToString()) > 0)
                {

                    //用户还的利息=总利息-体验金利息
                    amt = amt - decimal.Parse(dtlx.Rows[0]["lixi"].tostr());

                    //商户给投资人的优惠金的利息
                    //shanghutuihuan(dr["toubiaorenid"].ToString(), decimal.Parse(dtlx.Rows[0]["lixi"].tostr()));
                }

                objsend.TransAmt = amt.ToString("#0.00") + "";

                objsend.Fee = ConfigurationManager.AppSettings["RepaymentFee"];//费率为0
                objsend.InCustId = dr["UsrCustId"] + "";
                objsend.InAcctId = "";
                objsend.DivDetails = "";
                objsend.DivCustId = "";
                objsend.DivAcctId = "";
                objsend.DivAmt = "";
                objsend.FeeObjFlag = "";
                objsend.BgRetUrl = ConfigurationManager.AppSettings["LocalUrl"] + "ploan/zidonghuankuanreturnbg.html";
                objsend.ReqExt = "";
                objsend.ProId = "";

                ////进行调用之前，先产生流水  操作这个表dbo.Mautopayback 把里面的信息补充完整
                //LxwData data = new LxwData();
                ////data["xxxx"] = "xxxx";
                ////LogType 0 代表未处理，1代表已经处理
                //data["LogType"] = "0";
                //data["User_Id"] = HttpContext.Current.Session["g_user_id"].ToString(); ;//用户ID
                //data["OrdId"] = dr["OrdId"] + "";//订单号    
                //data["SubOrdDate"] = objsend.SubOrdDate + "";//设置日期
                //data["OrdDate"] = objsend.OrdDate + "";//订单日期
                //data["OutCustId"] = dr["BorrowerCustId"] + ""; //出账客户号
                //data["TransAmt"] = amt.ToString("#0.00") + ""; //交易金额
                //data["SubOrdId"] = dr["OrdId"] + "";//订单号
                //data["InCustId"] = dr["UsrCustId"] + "";//入账客户号
                ////data["ProId"] = proid.tostr();//入账客户号
                //var ret = lxwdbhelper.createorupdate(data, "Mautopaybackid");


                ////把主键设置上
                //objsend.MerPriv = ret.identity + "";


                //var r = WebPost.Send<RetRepayment>(objsend);
                //if (r.RespCode == "000")
                {
                    //LxwData Mautopayback = new LxwData();
                    ////返回原来投标记录的主键
                    //Mautopayback["Mautopaybackid"] = r.MerPriv + "";
                    ////Mautoappropriation["FreezeTrxId"] = objrev.FreezeTrxId;
                    ////Mautoappropriation["TrxId"] = objrev.TrxId;
                    //Mautopayback["FeeObjFlag"] = r.FeeObjFlag;//续费收取对象标志 I/O
                    //Mautopayback["MerCustId"] = r.MerCustId;//客户号
                    ////代表放款成功
                    //Mautopayback["logtype"] = "1";
                    ////更新信息
                    //lxwdbhelper.createorupdate(Mautopayback, "Mautopaybackid");
                    ////更新还款计划表状态

                    ////生成还款计划明细记录
                    //LxwData datahkmingxi = new LxwData();
                    //datahkmingxi["pjkjbxxid"] = drhk["pjkjbxxid"].tostr();
                    //datahkmingxi["jiekuanbiaoti"] = drhk["jiekuanbiaoti"].tostr();
                    //datahkmingxi["qishu"] = drhk["qishu"] + "";
                    //datahkmingxi["phkid"] = ParamsValue("phkid");
                    //datahkmingxi["user_id"] = jiandansql.getstring("select user_id from SysUser_kuozhan where UsrCustId='" + dr["UsrCustId"] + "'");
                    //datahkmingxi["huankuanjine"] = amt.ToString("#0.00") + "";
                    //datahkmingxi["zhuangtai"] = "已还款";
                    //datahkmingxi["huankuanrenid"] = HttpContext.Current.Session["g_user_id"].ToString() + "";
                    //datahkmingxi["huankuanleixing"] = "手动还款";
                    //lxwdbhelper.createorupdate(datahkmingxi, "phkmingxiid");
                    //int result = jiandansql.execute(" UPDATE  [dbo].[Project_TouZiJiLu] SET [PlanStatus]=2 WHERE  [PlanStatus]=0 AND  phkid=" + ParamsValue("phkid").toint32() + " AND  [OrdId]='" + dr["OrdId"].tostr() + "' AND [OrdDate]='" + dr["OrdDate"].tostr() + "'");

                    //发送短信
                    //string MOBIL_NO = jiandansql.getstring("select MOBIL_NO from SysUser where user_id='" + dr["toubiaorenid"].ToString() + "'");
                    //SMSApp.SendMsg(MOBIL_NO, "亲爱的嘉金投资用户,您好！感谢您使用互联网理财投资平台嘉金网。您投资的理财产品已提前获得应有收益，本金 已归还，您可以进行提现操作或者投资获得更大的收益。若您有其他问题，请您联系致电客服：400-100-0616。");
                    ////发送站内信
                    //P2PHelper.sendMessage(dr["toubiaorenid"].ToString(), "亲爱的嘉金投资用户,您好！感谢您使用互联网理财投资平台嘉金网。您投资的理财产品已提前获得应有收益，本金 已归还，您可以进行提现操作或者投资获得更大的收益。若您有其他问题，请您联系致电客服：400-100-0616。");
                //}
                //else { error++; }

            }
            if (error == 0)
            {
                //jiandansql.execute("update phk set zhuangtai='已还款',shijidaokuanriqi=GETDATE()  where  phkid=" + ParamsValue("phkid"));
                //jshelper.alertandredirect("还款成功！", "/puser/user_huankuanguanli.html");
            }
            else
            {
                //jshelper.alertandredirect("其中" + error.tostr() + "笔还款失败！", "/puser/user_huankuanguanli.html");
            }
            return;
        }
        //[SkipFilter()]
        //public void sendMsgbyjxg()
        //{
        //    this.CancelView();
        //    DataRowCollection res = jiandansql.getrows("SELECT * FROM pjktzjl WHERE pjkjbxxid=24 AND zhuangtai='正常'");
        //    foreach (DataRow dr in res)
        //    {
        //        decimal amount1 = jiandansql.getdecimal("SELECT SUM(interest) FROM dbo.PBenefitPlan WHERE pjktzjlid=" + dr["pjktzjlid"] + " AND PlanStatus=2");
        //        decimal amount2 = jiandansql.getdecimal("SELECT SUM(Principal) FROM dbo.PBenefitPlan WHERE pjktzjlid=" + dr["pjktzjlid"] + " AND PlanStatus=2");
        //        //string username = jiandansql.getstring("select USER_NAME from SysUser where user_id='" + dr["toubiaorenid"].ToString() + "'");
        //        //发送短信
        //        string MOBIL_NO = jiandansql.getstring("select MOBIL_NO from SysUser where user_id='" + dr["toubiaorenid"].ToString() + "'");
        //        SMSApp.SendMsg(MOBIL_NO, "尊敬的用户,您好！感谢您使用互联网理财投资平台-嘉金金融，您投资的理财产品嘉现贷【JXD20150304-019】已提前获得应有收益" + amount1.ToString("F2") + "元，并已归还本金" + amount2.ToString("F2") + "元，您可以进行提现操作或者投资获得更大的收益。若您有其他问题，请拨打客服热线：400-100-0616");
        //        //发送站内信
        //        P2PHelper.sendMessage(dr["toubiaorenid"].ToString(), "尊敬的用户,您好！感谢您使用互联网理财投资平台-嘉金金融，您投资的理财产品嘉现贷【JXD20150304-019】已提前获得应有收益" + amount1.ToString("F2") + "元，并已归还本金" + amount2.ToString("F2") + "元，您可以进行提现操作或者投资获得更大的收益。若您有其他问题，请拨打客服热线：400-100-0616");
        //    }

        //}

        #region OA还款 Create By JXG
        ////OA还款  从商户账户还款到投资人账户
        //public void oahuankuan()
        //{
        //    this.CancelView();
        //    string phkid = CryptoHelper.Decrypt(ParamsValue("phkid"));
        //    //按照计划，每次还款金额加上利息，还给投资人。
        //    //这里需要得到一些信息
        //    //首先需要得到标的相关信息
        //    //其次要得到投资人列表
        //    //然后是还款金额（分期本金+利息）
        //    DataRow drhk = jiandansql.getonerow("select pjkjbxxid,qishu,huankuanrenid,jiekuanbiaoti,(huankuanbenjin+lixi) as benxi  from phk where phkid=" + phkid);
        //    Decimal benxi = decimal.Parse(drhk["benxi"].tostr());
        //    //验证当前余额是否大于还款金额
        //    try
        //    {
        //        string zongjine = "";
        //        string dongjieyue = "";
        //        if (Decimal.Parse(P2PHelper.gethuifuzhanghuyue("", out zongjine, out dongjieyue, 1)) < benxi)
        //        {
        //            jshelper.alertandback("您的账户余额不足！");
        //            return;
        //        }
        //    }
        //    catch
        //    {
        //        jshelper.alertandback("您的账户余额不足！");
        //        return;
        //    }
        //    //查找所有未收益且有效（）的收益计划
        //    var sqlList = "SELECT * FROM [dbo].[Project_TouZiJiLu] WHERE PlanStatus=0 AND phkid=" + phkid;

        //    //todo 获取到投资该产品的投标记录，这些记录已经成功。shifouzhuanrang标识是否为转让债权
        //    //var sql = "select *,(select jiekuanjine from pjkjbxx where pjkjbxx.pjkjbxxid=Mmanualbid.ProId) as jiekuanjine,(select top 1 ProId from zhaiquanzhuanrang inner join  Mzhaiquanliushui on zhaiquanzhuanrang.pjkjbxxid=Mzhaiquanliushui.ProId where oldpjkjbxxid=" + drhk["pjkjbxxid"].tostr() + " and LogType=1) as shifouzhuanrang from Mmanualbid where LogType='1' and proid=" + drhk["pjkjbxxid"].tostr();
        //    var list = jiandansql.gettable(sqlList);
        //    if (list != null)
        //    {
        //        string InCustId = ""; //入账子客户号
        //        string SubOrdId = "";//订单号
        //        string SubOrdDate = "";//订单日期
        //        //循环进行放款
        //        foreach (DataRow dr in list.Rows)
        //        {
        //            Decimal PrincipalInterest = decimal.Parse(dr["Principal"].ToString()) + decimal.Parse(dr["Interest"].ToString());
        //            //还款
        //            oahuankuanhuifu(Decimal.Parse(dr["TransAmt"].tostr()), 0M, PrincipalInterest, dr["UsrCustId"].tostr(), dr["OrdId"].tostr(), dr["OrdDate"].tostr(), drhk["pjkjbxxid"].toint32(0), drhk["jiekuanbiaoti"].tostr(), drhk["qishu"].toint32(0), phkid.toint32(0), dr["UsrCustId"].tostr());

        //        }
        //        //更新还款计划表状态
        //        jiandansql.execute("update phk set zhuangtai='已还款',shijidaokuanriqi=GETDATE()  where  phkid=" + phkid);
        //        //jshelper.alertandredirect("还款成功！", "/Pjkjbxx/hklist.html?pjkjbxxid=" + drhk["pjkjbxxid"].tostr());
        //        jshelper.alertandclose("还款成功！");
        //    }
        //    return;
        //}

        ////OA还款调汇付接口
        //[SkipFilter()]
        //public void oahuankuanhuifu(Decimal TransAmt, Decimal jiekuanjine, Decimal benxi, string InCustId, string SubOrdId, string SubOrdDate, int pjkjbxxid, string jiekuanbiaoti, int qishu, int phkid, string UsrCustId)
        //{
        //    Repayment objsend = new Repayment();
        //    objsend.OrdId = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        //    objsend.OrdDate = DateTime.Now.ToString("yyyyMMdd");
        //    objsend.OutCustId = ConfigurationManager.AppSettings["MerCustId"] + "";
        //    //返款金额，这里需要计算，到底给该用户返款多少，需要计算出来这次返款+利息
        //    //Decimal amt = (TransAmt / jiekuanjine) * benxi;
        //    Decimal amt = benxi;
        //    objsend.TransAmt = amt.ToString("#0.00") + "";
        //    objsend.Fee = ConfigurationManager.AppSettings["RepaymentFee"];//费率为0
        //    //也是跟投标的时候 订单号和日期一致。
        //    objsend.SubOrdId = SubOrdId;
        //    objsend.SubOrdDate = SubOrdDate;
        //    objsend.OutAcctId = ConfigurationManager.AppSettings["AcctId"] + "";//出账子账户
        //    objsend.InCustId = InCustId;
        //    objsend.InAcctId = "";
        //    objsend.DivDetails = "";
        //    objsend.DivCustId = "";
        //    objsend.DivAcctId = "";
        //    objsend.DivAmt = "";
        //    objsend.FeeObjFlag = "";
        //    objsend.BgRetUrl = ConfigurationManager.AppSettings["LocalUrl"] + "ploan/zidonghuankuanreturnbg.html";
        //    objsend.ReqExt = "";
        //    objsend.ProId = "";
        //    //进行调用之前，先产生流水  操作这个表dbo.Mautopayback 把里面的信息补充完整
        //    //用户ID
        //    string user_id = jiandansql.getstring("select user_id from SysUser_kuozhan where UsrCustId='" + UsrCustId + "'"); //用户ID
        //    LxwData data = new LxwData();
        //    data["LogType"] = "0"; //LogType 0 代表未处理，1代表已经处理
        //    data["User_Id"] = user_id;
        //    data["OrdId"] = objsend.OrdId + "";//订单号    
        //    data["SubOrdDate"] = objsend.SubOrdDate + "";//设置日期
        //    data["OrdDate"] = objsend.OrdDate + "";//订单日期
        //    data["OutCustId"] = ConfigurationManager.AppSettings["MerCustId"] + ""; //出账客户号
        //    data["OutAcctId"] = ConfigurationManager.AppSettings["AcctId"] + "";//出账子账户
        //    data["TransAmt"] = amt.ToString("#0.00") + ""; //交易金额
        //    data["SubOrdId"] = SubOrdId + "";//订单号
        //    data["InCustId"] = InCustId;//入账客户号
        //    //data["ProId"] = proid.tostr();//入账客户号
        //    var ret = lxwdbhelper.createorupdate(data, "Mautopaybackid");

        //    //把主键设置上
        //    objsend.MerPriv = ret.identity + "";
        //    var r = WebPost.Send<RetRepayment>(objsend);
        //    if (r.RespCode == "000")
        //    {
        //        LxwData Mautopayback = new LxwData();
        //        //返回原来投标记录的主键
        //        Mautopayback["Mautopaybackid"] = r.MerPriv + "";
        //        //Mautoappropriation["FreezeTrxId"] = objrev.FreezeTrxId;
        //        //Mautoappropriation["TrxId"] = objrev.TrxId;
        //        Mautopayback["FeeObjFlag"] = r.FeeObjFlag;//续费收取对象标志 I/O
        //        Mautopayback["MerCustId"] = r.MerCustId;//客户号
        //        //代表放款成功
        //        Mautopayback["logtype"] = "1";
        //        //更新信息
        //        lxwdbhelper.createorupdate(Mautopayback, "Mautopaybackid");



        //        //生成还款计划明细记录
        //        LxwData datahkmingxi = new LxwData();
        //        datahkmingxi["pjkjbxxid"] = pjkjbxxid.tostr();
        //        datahkmingxi["jiekuanbiaoti"] = jiekuanbiaoti;
        //        datahkmingxi["qishu"] = qishu + "";
        //        datahkmingxi["phkid"] = phkid + "";
        //        datahkmingxi["user_id"] = jiandansql.getstring("select user_id from SysUser_kuozhan where UsrCustId='" + InCustId + "'");
        //        datahkmingxi["huankuanjine"] = amt.ToString("#0.00") + "";
        //        datahkmingxi["zhuangtai"] = "已还款";
        //        datahkmingxi["huankuanrenid"] = user_id + "";
        //        datahkmingxi["huankuanleixing"] = "OA还款";
        //        lxwdbhelper.createorupdate(datahkmingxi, "phkmingxiid");


        //        //更新收益计划的状态 By JXG
        //        int result = jiandansql.execute(" UPDATE  [dbo].[Project_TouZiJiLu] SET [PlanStatus]=2 WHERE phkid=" + phkid + " AND  [OrdId]='" + SubOrdId + "' AND [OrdDate]='" + SubOrdDate + "'");

        //    }
        }

        #region OA还款 old
        //OA还款  从商户账户还款到投资人账户
        //[SkipFilter()]
        //public void oahuankuan()
        //{
        //    this.CancelView();

        //    //按照计划，每次还款金额加上利息，还给投资人。
        //    //这里需要得到一些信息
        //    //首先需要得到标的相关信息
        //    //其次要得到投资人列表
        //    //然后是还款金额（分期本金+利息）
        //    DataRow drhk = jiandansql.getonerow("select pjkjbxxid,qishu,huankuanrenid,jiekuanbiaoti,(huankuanbenjin+lixi) as benxi  from phk where phkid=" + ParamsValue("phkid"));
        //    Decimal benxi = decimal.Parse(drhk["benxi"].tostr());
        //    //验证当前余额是否大于还款金额
        //    try
        //    {
        //        string zongjine = "";
        //        string dongjieyue = "";
        //        if (Decimal.Parse(P2PHelper.gethuifuzhanghuyue("", out zongjine, out dongjieyue, 1)) < benxi)
        //        {
        //            jshelper.alertandback("您的账户余额不足！");
        //            return;
        //        }
        //    }
        //    catch
        //    {
        //        jshelper.alertandback("您的账户余额不足！");
        //        return;
        //    }
        //    //var planList = "SELECT * FROM [dbo].[Project_TouZiJiLu] WHERE (Deadline<GETDATE()+1 OR Deadline<GETDATE())  AND PlanStatus=0  pjkjbxxid= " + drhk["pjkjbxxid"].tostr();

        //    //todo 获取到投资该产品的投标记录，这些记录已经成功。shifouzhuanrang标识是否为转让债权
        //    var sql = "select *,(select jiekuanjine from pjkjbxx where pjkjbxx.pjkjbxxid=Mmanualbid.ProId) as jiekuanjine,(select top 1 ProId from zhaiquanzhuanrang inner join  Mzhaiquanliushui on zhaiquanzhuanrang.pjkjbxxid=Mzhaiquanliushui.ProId where oldpjkjbxxid=" + drhk["pjkjbxxid"].tostr() + " and LogType=1) as shifouzhuanrang from Mmanualbid where LogType='1' and proid=" + drhk["pjkjbxxid"].tostr();
        //    var list = jiandansql.getrows(sql);
        //    if (list != null)
        //    {
        //        string InCustId = ""; //入账子客户号
        //        string SubOrdId = "";//订单号
        //        string SubOrdDate = "";//订单日期
        //        //循环进行放款
        //        foreach (DataRow dr in list)
        //        {
        //            //判断是否转让债权
        //            if (dr["shifouzhuanrang"].toint32(0) > 0)
        //            {
        //                var zhiquanlist = jiandansql.getrows("select * from Mzhaiquanliushui where ProId=" + dr["shifouzhuanrang"].toint32(0) + " and LogType=1");
        //                if (zhiquanlist != null)
        //                {
        //                    foreach (DataRow zhaiquandr in zhiquanlist)
        //                    {//债权还款
        //                        oahuankuanhuifu(Decimal.Parse(zhaiquandr["CreditDealAmt"].tostr()), Decimal.Parse(dr["jiekuanjine"].tostr()), benxi, zhaiquandr["BuyCustId"].tostr(), zhaiquandr["OrdId"].tostr(), zhaiquandr["OrdDate"].tostr(), drhk["pjkjbxxid"].toint32(0), drhk["jiekuanbiaoti"].tostr(), drhk["qishu"].toint32(0), ParamsValue("phkid").toint32(0), dr["UsrCustId"].tostr());
        //                    }
        //                }

        //            }
        //            else
        //            {
        //                //还款
        //                oahuankuanhuifu(Decimal.Parse(dr["TransAmt"].tostr()), Decimal.Parse(dr["jiekuanjine"].tostr()), benxi, dr["UsrCustId"].tostr(), dr["OrdId"].tostr(), dr["OrdDate"].tostr(), drhk["pjkjbxxid"].toint32(0), drhk["jiekuanbiaoti"].tostr(), drhk["qishu"].toint32(0), ParamsValue("phkid").toint32(0), dr["UsrCustId"].tostr());
        //            }
        //        }
        //        jshelper.alertandredirect("还款成功！", "/Pjkjbxx/hklist.html?pjkjbxxid=" + drhk["pjkjbxxid"].tostr());
        //    }
        //    return;
        //}
        #endregion

        #endregion



        #endregion

        /// <summary>
        /// 自动还款，20141113 lxw 在王春燕的基础上做一些调整。
        /// </summary>
        //void shoudonghuankuan_auto(string[] pstr)
        //{
        //    this.CancelView();
        //    //传递过来的参数，必须进行解密，
        //    if (pstr.Length != 2) return;


        //    this.CancelView();
        //    DataRow drhk = jiandansql.getonerow("select pjkjbxxid,qishu,huankuanrenid,jiekuanbiaoti,(huankuanbenjin+lixi) as benxi  from phk where phkid=" + pstr[0]);
        //    Decimal benxi = decimal.Parse(drhk["benxi"].tostr());
        //    //验证当前余额是否大于还款金额
        //    try
        //    {
        //        string zongjine = "";
        //        string dongjieyue = "";
        //        if (Decimal.Parse(P2PHelper.gethuifuzhanghuyue(pstr[1], out zongjine, out dongjieyue, 0)) < benxi)
        //        {
        //            return;
        //        }
        //    }
        //    catch
        //    {

        //        return;
        //    }

        //    //todo 获取到投资该产品的投标记录，这些记录已经成功。
        //    var sql = "select *,(select jiekuanjine from pjkjbxx where pjkjbxx.pjkjbxxid=Mmanualbid.ProId) as jiekuanjine from Mmanualbid where LogType='1' and proid=" + drhk["pjkjbxxid"].tostr();
        //    var list = jiandansql.getrows(sql);

        //    //循环进行放款
        //    foreach (DataRow dr in list)
        //    {

        //        Repayment objsend = new Repayment();

        //        objsend.OrdId = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        //        objsend.OrdDate = DateTime.Now.ToString("yyyyMMdd");
        //        objsend.OutCustId = dr["BorrowerCustId"] + "";

        //        //也是跟投标的时候 订单号和日期一致。
        //        objsend.SubOrdId = dr["OrdId"] + "";
        //        objsend.SubOrdDate = dr["OrdDate"] + "";

        //        objsend.OutAcctId = "";

        //        //返款金额，这里需要计算，到底给该用户返款多少，需要计算出来这次返款+利息
        //        Decimal amt = (Decimal.Parse(dr["TransAmt"].tostr()) / Decimal.Parse(dr["jiekuanjine"].tostr())) * benxi;
        //        objsend.TransAmt = amt.ToString("#0.00") + "";
        //        objsend.Fee = ConfigurationManager.AppSettings["RepaymentFee"];//费率为0
        //        objsend.InCustId = dr["UsrCustId"] + "";
        //        objsend.InAcctId = "";
        //        objsend.DivDetails = "";
        //        objsend.DivCustId = "";
        //        objsend.DivAcctId = "";
        //        objsend.DivAmt = "";
        //        objsend.FeeObjFlag = "";
        //        objsend.BgRetUrl = ConfigurationManager.AppSettings["LocalUrl"] + "ploan/zidonghuankuanreturnbg.html";
        //        objsend.ReqExt = "";
        //        objsend.ProId = "";

        //        //进行调用之前，先产生流水  操作这个表dbo.Mautopayback 把里面的信息补充完整
        //        LxwData data = new LxwData();
        //        //data["xxxx"] = "xxxx";
        //        //LogType 0 代表未处理，1代表已经处理
        //        data["LogType"] = "0";
        //        data["User_Id"] = pstr[1];//用户ID
        //        data["OrdId"] = dr["OrdId"] + "";//订单号    
        //        data["SubOrdDate"] = objsend.SubOrdDate + "";//设置日期
        //        data["OrdDate"] = objsend.OrdDate + "";//订单日期
        //        data["OutCustId"] = dr["BorrowerCustId"] + ""; //出账客户号
        //        data["TransAmt"] = amt.ToString("#0.00") + ""; //交易金额
        //        data["SubOrdId"] = dr["OrdId"] + "";//订单号
        //        data["InCustId"] = dr["UsrCustId"] + "";//入账客户号
        //        //data["ProId"] = proid.tostr();//入账客户号
        //        var ret = lxwdbhelper.createorupdate(data, "Mautopaybackid");
        //        //把主键设置上
        //        objsend.MerPriv = ret.identity + "";
        //        var r = WebPost.Send<RetRepayment>(objsend);
        //        if (r.RespCode == "000")
        //        {
        //            LxwData Mautopayback = new LxwData();
        //            //返回原来投标记录的主键
        //            Mautopayback["Mautopaybackid"] = r.MerPriv + "";
        //            //Mautoappropriation["FreezeTrxId"] = objrev.FreezeTrxId;
        //            //Mautoappropriation["TrxId"] = objrev.TrxId;
        //            Mautopayback["FeeObjFlag"] = r.FeeObjFlag;//续费收取对象标志 I/O
        //            Mautopayback["MerCustId"] = r.MerCustId;//客户号
        //            //代表放款成功
        //            Mautopayback["logtype"] = "1";
        //            //更新信息
        //            lxwdbhelper.createorupdate(Mautopayback, "Mautopaybackid");
        //            //更新还款计划表状态
        //            jiandansql.execute("update phk set zhuangtai='已还款',shijidaokuanriqi=GETDATE()  where  phkid=" + pstr[0]);
        //            //生成还款计划明细记录
        //            LxwData datahkmingxi = new LxwData();
        //            datahkmingxi["pjkjbxxid"] = drhk["pjkjbxxid"].tostr();
        //            datahkmingxi["jiekuanbiaoti"] = drhk["jiekuanbiaoti"].tostr();
        //            datahkmingxi["qishu"] = drhk["qishu"] + "";
        //            datahkmingxi["phkid"] = pstr[0];
        //            datahkmingxi["user_id"] = jiandansql.getstring("select user_id from SysUser_kuozhan where UsrCustId='" + dr["UsrCustId"] + "'");
        //            datahkmingxi["huankuanjine"] = amt.ToString("#0.00") + "";
        //            datahkmingxi["zhuangtai"] = "已还款";
        //            datahkmingxi["huankuanrenid"] = pstr[1] + "";
        //            datahkmingxi["huankuanleixing"] = "自动还款";
        //            lxwdbhelper.createorupdate(datahkmingxi, "phkmingxiid");

        //        }

        //    }
        //    return;
        //}

        ///// <summary>
        ///// 这个方法，对外界开放调用。建议只开一个线程，否则会出现线程方面的业务问题
        ///// </summary>
        //[SkipFilter()]
        //public void user_huankuanguanli_auto()
        //{
        //    //这个方法，由服务器的winform程序，每隔30秒调用一次。
        //    string sql = "select top 20 a.phkid,a.huankuanrenid from phk a left join pjkjbxx b on a.pjkjbxxid=b.pjkjbxxid where b.zidonghuankuan=1 and  a.zhuangtai='未还款'  and  getdate() > DATEadd(HOUR,isnull(b.dangtianjidian,0), DATEadd(day,isnull(b.tiqiantianshu,0)-(isnull(b.tiqiantianshu,0)*2), a.huankuanriqi)) order by a.huankuanriqi asc";//where 

        //    var drs = jiandansql.getrows(sql);
        //    foreach (DataRow dr in drs)
        //    {
        //        //调用他们进行还款。
        //        shoudonghuankuan_auto(new string[] { dr["phkid"].tostr(), dr["huankuanrenid"].tostr() });
        //    }

        //    this.CancelView();
        //    Response.Write("执行成功:" + drs.Count);

        //}

        
    }
}